package com.example.lin.day9_25_rxjava;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {


    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView tv_show;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_show = findViewById(R.id.tv_show);
        findViewById(R.id.btn_load).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                test3();
            }
        });

    }

    private void test3() {

        Disposable subscribe = Observable.create(new ObservableOnSubscribe<MyLocation>() {
            @Override
            public void subscribe(ObservableEmitter<MyLocation> emitter) throws Exception {
                OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).build();

                Request request = new Request.Builder().url("http://location.ximalaya.com/location-web/location?latitude=22.535456&longitude=114.013493")
                        .get().build();

                Call call = client.newCall(request);

                Response response = call.execute();

                ResponseBody body = response.body();

                if (body != null) {
                    String jsonStr = body.string();
                    MyLocation myLocation = new Gson().fromJson(jsonStr, MyLocation.class);
                    emitter.onNext(myLocation);
                    emitter.onComplete();
                } else {
                    emitter.onError(new NullPointerException("body is null!"));
                }
                //请求网络
//                emitter.onNext();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Consumer<MyLocation>() {
                    @Override
                    public void accept(MyLocation myLocation) throws Exception {
                        tv_show.setText(myLocation.toString());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        Toast.makeText(MainActivity.this, "啊哈哈", Toast.LENGTH_SHORT).show();
                    }
                }, new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                });

//                .subscribe(new Observer<MyLocation>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(MyLocation myLocation) {
//                        tv_show.setText(myLocation.toString());
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });


    }


    /**
     * 响应式编程,链式调用 RXjava
     */
    private void test2() {

        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                Log.d(TAG, "subscribe: " + Thread.currentThread().getName());
                emitter.onNext(new ArrayList<String>());
            }
        })
                //指定 订阅关系发生在 子线程中,默认情况下,被观察者 与 观察者都在子线程中
                .subscribeOn(Schedulers.io())
                //指定 观察者在 UI线程中 观察
                .observeOn(AndroidSchedulers.mainThread())

                //开始订阅
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<String> strings) {
                        //刷新适配器...
                        tv_show.setText("爱上了对方即可");
                        tv_show.setTextSize(12);
                        Toast.makeText(MainActivity.this, "子线程都能Toast马", Toast.LENGTH_SHORT).show();
                        Log.d(TAG, "onNext: " + Thread.currentThread().getName());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    /**
     * RxJava的基本使用
     */
    private void test1() {
        Observable<String> 被观察者 = Observable.create(new ObservableOnSubscribe<String>() {

            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                Log.e(TAG, "subscribe: ");
                //网络请求成功!
                emitter.onNext("小说1");
                emitter.onNext("小说2");
                emitter.onNext("小说3");
                emitter.onNext("小说4");
                emitter.onNext("555");
                emitter.onNext("小说6");
                emitter.onNext("小说7");
                emitter.onNext("小说8");

                //onError与onComplete 互斥.onError之后onComplete不响应.而onComplete之后 onError 异常无人处理,所有整个订阅会因此发生异常
//                emitter.onError(new NullPointerException("嘻嘻嘻嘻"));
                //throw new NullPointerException("哈哈哈哈");//与emitter.onError 等价
                emitter.onComplete();
            }
        });

        Observer<String> 观察者 = new Observer<String>() {

            /**
             * 观察者成功 订阅了  被观察者
             *
             * 在 被观察者的 subscribe(ObservableEmitter<String> emitter) 之前被调用
             *
             * @param d  d.isDisposed() 判断是否还可以订阅,false可以订阅,true不再订阅.
             *           d.dispose();结束订阅 ,之后onNext,onComplete,onError 都不在响应
             */
            @Override
            public void onSubscribe(Disposable d) {
                this.d = d;
                Log.d(TAG, "onSubscribe: " + d.isDisposed());
            }

            private Disposable d;

            /**
             *
             * 当 被观察者的 subscribe(ObservableEmitter<String> emitter)  的 emitter的onNext()被调用,则该方法被调用
             *
             * 可以被调用多次
             *
             * @param s emitter的onNext(value) 的value 值
             */
            @Override
            public void onNext(String s) {
                Log.i(TAG, "onNext: " + s);
//                if ("555".equals(s)){
//                    d.dispose();
//                }
            }

            /**
             * 被观察的 subscribe 发生异常,该方法被调用
             * 或者 被观察者的 subscribe(ObservableEmitter<String> emitter)  的 emitter的onError()被调用,
             * @param e 发生的异常对象
             */
            @Override
            public void onError(Throwable e) {
                Log.e(TAG, "onError: " + e.toString());
            }

            /**
             *
             * 当 被观察者的 subscribe(ObservableEmitter<String> emitter)  的 emitter的onComplete()被调用,则该方法被调用,表示完成订阅
             *
             * 该方法只会触发1次
             *
             * 该方法之后 onNext 将不会被调用
             *
             */
            @Override
            public void onComplete() {
                Log.w(TAG, "onComplete: ");
            }
        };

        //被观察者 被 观察者 订阅了 ,  被观察者的 subscribe 方法会立刻被调用
        被观察者.subscribe(观察者);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        test2();
    }
}
